﻿Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Text
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Text.RegularExpressions

Namespace DotNetNuke.Modules.ActiveForums.Controls
    <DefaultProperty("Text"), ToolboxData("<{0}:WhatsNewRSS runat=server></{0}:WhatsNewRSS>")> _
    Public Class WhatsNewRSS
        Inherits Control

        Dim dblCacheTimeOut As Double
        Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
            Dim intTabId As Integer = -1
            Dim intModuleId As Integer = -1
            Dim intPortalId As Integer = 0
            'Response.Write(intPortalId)
            If Not HttpContext.Current.Request.QueryString("tabid") Is Nothing Then
                If IsNumeric(HttpContext.Current.Request.QueryString("tabid")) Then
                    intTabId = CType(HttpContext.Current.Request.QueryString("tabid"), Integer)
                End If
            End If
            If Not HttpContext.Current.Request.QueryString("moduleid") Is Nothing Then
                If IsNumeric(HttpContext.Current.Request.QueryString("moduleid")) Then
                    intModuleId = CType(HttpContext.Current.Request.QueryString("moduleid"), Integer)
                End If
            End If
            If Not HttpContext.Current.Request.QueryString("portalid") Is Nothing Then
                If IsNumeric(HttpContext.Current.Request.QueryString("portalid")) Then
                    intPortalId = CType(HttpContext.Current.Request.QueryString("portalid"), Integer)
                End If
            End If
            If intTabId = -1 Or intModuleId = -1 Then
                Exit Sub
            End If
            Dim intPosts As Integer
            Dim mc As New DotNetNuke.Entities.Modules.ModuleController
            Dim settings As Hashtable = mc.GetModuleSettings(intModuleId)
            If Not CType(settings("AFTopPostsNumber"), String) Is Nothing Then
                intPosts = CType(settings("AFTopPostsNumber"), Integer)
            Else
                intPosts = 5
            End If
            Dim sForums As String = String.Empty
            If Not CType(settings("AFTopPostsForums"), String) Is Nothing Then
                sForums = CType(settings("AFTopPostsForums"), String)
            End If
            Dim bolSecurity As Boolean
            Dim bolBody As Boolean
            If Not CType(settings("AFTopPostsSecurity"), String) Is Nothing Then
                bolSecurity = CType(settings("AFTopPostsSecurity"), Boolean)
            End If
            If Not CType(settings("AFTopPostsBody"), String) Is Nothing Then
                bolBody = CType(settings("AFTopPostsBody"), Boolean)
            End If
            If Not CType(settings("AFTopPostsCache"), String) Is Nothing Then
                dblCacheTimeOut = CType(settings("AFTopPostsCache"), Integer)
            Else
                dblCacheTimeOut = 30
            End If
            'Response.Write(BuildRSS(intPortalId, intTabId, intModuleId, intPosts, sForums, bolSecurity, bolBody))
            Dim sOut As String = String.Empty
            If Not CType(settings("AFTopPostsRSS"), String) Is Nothing Then
                If CType(settings("AFTopPostsRSS"), Boolean) = True Then
                    Dim obj As Object = DataCache.CacheRetrieve("aftprss" & intModuleId)
                    If Not obj Is Nothing Then
                        sOut = CType(obj, String)
                    Else
                        sOut = BuildRSS(intModuleId, intPortalId)
                    End If
                End If

            End If


            writer.Write(sOut)
            MyBase.Render(writer)
        End Sub
        'Protected Overrides Sub RenderContents(ByVal writer As HtmlTextWriter)

        'End Sub
        Private Function WriteElement(ByVal Element As String, ByVal Indent As Integer) As String
            Dim InputLength As Integer = Element.Trim.Length + 20
            Dim sb As New StringBuilder(InputLength)
            sb.Append(ControlChars.CrLf.PadRight(Indent + 2, ControlChars.Tab))
            sb.Append("<").Append(Element).Append(">")
            Return sb.ToString
        End Function

        Private Function WriteElement(ByVal Element As String, ByVal ElementValue As String, ByVal Indent As Integer) As String
            Dim InputLength As Integer = Element.Trim.Length + ElementValue.Trim.Length + 20
            Dim sb As New StringBuilder(InputLength)
            sb.Append(ControlChars.CrLf.PadRight(Indent + 2, ControlChars.Tab))
            sb.Append("<").Append(Element).Append(">")
            sb.Append(CleanXmlString(ElementValue))
            sb.Append("</").Append(Element).Append(">")
            Return sb.ToString
        End Function

        Private Function CleanXmlString(ByVal XmlString As String) As String
            XmlString = HttpContext.Current.Server.HtmlEncode(XmlString)
            Return XmlString
        End Function

        Private Sub WhatsNewRSS_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            ''Put user code to initialize the page here
            HttpContext.Current.Response.ContentType = "text/xml"
            HttpContext.Current.Response.ContentEncoding = Encoding.UTF8


            'HttpContext.Current.Response.Write(sOut)

        End Sub
        Private Function BuildRSS(ByVal ModuleId As Integer, ByVal PortalId As Integer) As String

            Dim settings As Hashtable = DotNetNuke.Entities.Portals.PortalSettings.GetModuleSettings(ModuleId)
            Dim forumids As String = String.Empty
            Dim bolTopicsOnly As Boolean
            Dim bolRandom As Boolean = False
            Dim Rows As Integer = 10
            Dim IgnoreSecurity As Boolean = False
            Dim IncludeBody As Boolean = False
            Dim bRSS As Boolean = False
            Dim tags As String = String.Empty
            If Not CType(settings("AFTopPostsTopicsOnly"), String) Is Nothing Then
                bolTopicsOnly = CType(settings("AFTopPostsTopicsOnly"), Boolean)
            End If
            If Not CType(settings("AFTopPostsRandomOrder"), String) Is Nothing Then
                bolRandom = CType(settings("AFTopPostsRandomOrder"), Boolean)
            End If
            If Not CType(settings("AFTopPostsForums"), String) Is Nothing Then
                forumids = CType(settings("AFTopPostsForums"), String)
            End If
            If Not CType(settings("AFTopPostsNumber"), String) Is Nothing Then
                Rows = CType(settings("AFTopPostsNumber"), Integer)
            End If
            If Not CType(settings("AFTopPostsRSS"), String) Is Nothing Then
                bRSS = CType(settings("AFTopPostsRSS"), Boolean)
            End If

            If Not CType(settings("AFTopPostsSecurity"), String) Is Nothing Then
                IgnoreSecurity = CType(settings("AFTopPostsSecurity"), Boolean)
            End If
            If Not CType(settings("AFTopPostsBody"), String) Is Nothing Then
                IncludeBody = CType(settings("AFTopPostsBody"), Boolean)
            End If
            If Not CType(settings("AFTopPostsTags"), String) Is Nothing Then
                tags = CType(settings("AFTopPostsTags"), String)
            End If
            Dim counter As Integer = 0
            Dim sb As New StringBuilder(1024)
            ' build header
            sb.Append("<?xml version=""1.0"" encoding=""utf-8""?>" & ControlChars.CrLf)
            sb.Append("<rss version=""2.0"" xmlns:atom=""http://www.w3.org/2005/Atom"" xmlns:cf=""http://www.microsoft.com/schemas/rss/core/2005"" xmlns:dc=""http://purl.org/dc/elements/1.1/"" xmlns:slash=""http://purl.org/rss/1.0/modules/slash/"">" & ControlChars.CrLf)



            ' build channel
            Dim pc As New DotNetNuke.Entities.Portals.PortalController
            Dim ps As DotNetNuke.Entities.Portals.PortalSettings = DotNetNuke.Entities.Portals.PortalController.GetCurrentPortalSettings
            Dim offSet As Integer = ps.TimeZoneOffset
            sb.Append(WriteElement("channel", 1))
            sb.Append(WriteElement("title", ps.PortalName, 2))
            sb.Append(WriteElement("link", "http://" & HttpContext.Current.Request.Url.Host, 2))
            sb.Append(WriteElement("description", ps.PortalName, 2))
            sb.Append(WriteElement("generator", "ActiveForums  4.1", 2))
            sb.Append(WriteElement("language", ps.DefaultLanguage, 2))
            'sb.Append(WriteElement("copyright", ps.FooterText, 2))
            If Not ps.LogoFile = String.Empty Then
                Dim sLogo As String = "<image><url>http://" & HttpContext.Current.Request.Url.Host & ps.HomeDirectory & ps.LogoFile & "</url>"
                sLogo &= "<title>" & ps.PortalName & "</title>"
                sLogo &= "<link>http://" & HttpContext.Current.Request.Url.Host & "</link></image>"
                sb.Append(sLogo)
            End If
            sb.Append(WriteElement("copyright", ps.FooterText, 2))
            'sb.Append(WriteElement("webMaster", ps.Email, 2))
            sb.Append(WriteElement("lastBuildDate", "[LASTBUILDDATE]", 2))

            Dim LastBuildDate As Date = Nothing
            ' build items
            Dim ui As DotNetNuke.Entities.Users.UserInfo
            ui = DotNetNuke.Entities.Users.UserController.GetCurrentUserInfo()
            Dim useFriendly As Boolean = Utilities.IsRewriteLoaded
            Dim dr As IDataReader = DataProvider.Instance.GetPosts(PortalId, forumids, True, False, Rows, ui.UserID, IgnoreSecurity, False, tags)
            Dim sHost As String = Utilities.GetHost()
            Try
                While dr.Read
                    Dim Indent As Integer = 2
                    Dim GroupName As String = String.Empty
                    Dim GroupId As String = String.Empty
                    Dim TopicTabId As String = String.Empty
                    Dim TopicModuleId As String = String.Empty
                    Dim ForumName As String = String.Empty
                    Dim ForumId As String = String.Empty
                    Dim Subject As String = String.Empty
                    Dim UserName As String = String.Empty
                    Dim PostDate As String = String.Empty
                    Dim Body As String = String.Empty
                    Dim BodyHTML As String = String.Empty
                    Dim DisplayName As String = String.Empty
                    Dim ReplyCount As String = String.Empty
                    Dim LastPostDate As String = String.Empty
                    Dim TopicId As String = String.Empty
                    Dim ReplyId As String = String.Empty
                    Dim FirstName As String = String.Empty
                    Dim LastName As String = String.Empty
                    Dim AuthorId As String = String.Empty

                    
                    Dim sForumUrl As String = String.Empty
                    Dim sTopicURL As String = String.Empty
                    Dim sGroupPrefixURL As String = String.Empty

                    GroupName = CStr(dr("GroupName"))
                    GroupId = CStr(dr("ForumGroupId"))
                    TopicTabId = CStr(dr("TabId"))
                    TopicModuleId = CStr(dr("ModuleId"))
                    ForumName = CStr(dr("ForumName"))
                    ForumId = CStr(dr("ForumId"))
                    Subject = CStr(dr("Subject"))
                    UserName = CStr(dr("AuthorUserName"))
                    FirstName = CStr(dr("AuthorFirstName"))
                    LastName = CStr(dr("AuthorLastName"))
                    AuthorId = CStr(dr("AuthorId"))
                    DisplayName = CStr(dr("AuthorDisplayName"))
                    PostDate = CStr(dr("DateCreated"))
                    Body = Utilities.StripHTMLTag(CStr(dr("Body")))
                    TopicId = CStr(dr("TopicId"))
                    ReplyId = CStr(dr("ReplyId"))
                    BodyHTML = CStr(dr("Body"))
                    ReplyCount = CStr(dr("ReplyCount"))
                    '  topicUrl = dr("URL").ToString
                    sForumUrl = dr("PrefixURL").ToString
                    sTopicURL = dr("TopicURL").ToString
                    sGroupPrefixURL = dr("GroupPrefixURL").ToString
                    If LastBuildDate = Nothing Then
                        LastBuildDate = CDate(dr("DateCreated")).AddMinutes(offSet)
                    Else
                        If CDate(dr("DateCreated")).AddMinutes(offSet) > LastBuildDate Then
                            LastBuildDate = CDate(dr("DateCreated")).AddMinutes(offSet)
                        End If
                    End If
                    Dim ts As SettingsInfo = DataCache.MainSettings(CInt(TopicModuleId))

                    'UserProfiles.GetDisplayName(CInt(AuthorId), ts.UserNameDisplay, False, UserName, FirstName, LastName, DisplayName)
                    Dim URL As String = String.Empty
                    If String.IsNullOrEmpty(sTopicURL) Or Not useFriendly Then
                        Dim Params As String() = {ParamKeys.ViewType & "=" & Views.Topic, ParamKeys.ForumId & "=" & ForumId, ParamKeys.TopicId & "=" & TopicId}
                        URL = DotNetNuke.Common.NavigateURL(CInt(TopicTabId), "", Params)
                        If URL.IndexOf(HttpContext.Current.Request.Url.Host) = -1 Then
                            URL = DotNetNuke.Common.AddHTTP(HttpContext.Current.Request.Url.Host) & URL
                        End If
                    Else
                        Dim ctlUtils As New ControlUtils
                        sTopicURL = ctlUtils.BuildUrl(CInt(TopicTabId), CInt(TopicModuleId), sGroupPrefixURL, sForumUrl, CInt(GroupId), CInt(ForumId), CInt(TopicId), sTopicURL, -1, -1, String.Empty, 1, -1)
                        If sHost.EndsWith("/") And sTopicURL.StartsWith("/") Then
                            sHost = sHost.Substring(0, sHost.Length - 1)
                        End If
                        URL = sHost & sTopicURL
                    End If
                    
                    'URL = URL.Replace("&", "&amp;")
                    sb.Append(WriteElement("item", Indent))

                    sb.Append(WriteElement("title", Subject, Indent + 1))
                    If IncludeBody = True Then
                        If BodyHTML.IndexOf("<body>") > 0 Then
                            BodyHTML = TemplateUtils.GetTemplateSection(BodyHTML, "<body>", "</body>")
                        End If
                        If BodyHTML.Contains("&#91;IMAGE:") Then
                            Dim strHost As String = DotNetNuke.Common.AddHTTP(DotNetNuke.Common.GetDomainName(HttpContext.Current.Request)) & "/"
                            Dim pattern As String = "(&#91;IMAGE:(.+?)&#93;)"
                            Dim regExp As New Regex(pattern)
                            Dim matches As MatchCollection
                            matches = regExp.Matches(BodyHTML)
                            For Each match As Match In matches
                                Dim sImage As String = ""
                                sImage = "<img src=""" & strHost & "DesktopModules/ActiveForums/viewer.aspx?portalid=" & PortalId & "&moduleid=" & ModuleId & "&attachid=" & match.Groups(2).Value & """ border=""0"" />"
                                BodyHTML = BodyHTML.Replace(match.Value, sImage)
                            Next match
                        End If
                        If BodyHTML.Contains("&#91;THUMBNAIL:") Then
                            Dim strHost As String = DotNetNuke.Common.AddHTTP(DotNetNuke.Common.GetDomainName(HttpContext.Current.Request)) & "/"
                            Dim pattern As String = "(&#91;THUMBNAIL:(.+?)&#93;)"
                            Dim regExp As New Regex(pattern)
                            Dim matches As MatchCollection
                            matches = regExp.Matches(BodyHTML)
                            For Each match As Match In matches
                                Dim sImage As String = ""
                                Dim thumbId As String = match.Groups(2).Value.Split(CChar(":"))(0)
                                Dim parentId As String = match.Groups(2).Value.Split(CChar(":"))(1)
                                sImage = "<a href=""" & strHost & "DesktopModules/ActiveForums/viewer.aspx?portalid=" & PortalId & "&moduleid=" & ModuleId & "&attachid=" & parentId & """ target=""_blank""><img src=""" & strHost & "DesktopModules/ActiveForums/viewer.aspx?portalid=" & PortalId & "&moduleid=" & ModuleId & "&attachid=" & thumbId & """ border=""0"" /></a>"
                                BodyHTML = BodyHTML.Replace(match.Value, sImage)
                            Next match
                        End If
                        BodyHTML = BodyHTML.Replace("src=""/Portals", "src=""" & DotNetNuke.Common.AddHTTP(HttpContext.Current.Request.Url.Host) & "/Portals")
                        BodyHTML = Utilities.ManageImagePath(BodyHTML, DotNetNuke.Common.AddHTTP(HttpContext.Current.Request.Url.Host))

                        sb.Append(WriteElement("description", BodyHTML, Indent + 1))
                    Else
                        sb.Append(WriteElement("description", String.Empty, Indent + 1))
                    End If
                    sb.Append(WriteElement("link", URL, Indent + 1))
                    sb.Append(WriteElement("comments", URL, Indent + 1))
                    sb.Append(WriteElement("pubDate", CDate(PostDate).AddMinutes(offSet).ToString("r"), Indent + 1))
                    sb.Append(WriteElement("dc:creator", DisplayName, Indent + 1))
                    sb.Append(WriteElement("guid", URL, Indent + 1))
                    sb.Append(WriteElement("slash:comments", ReplyCount, Indent + 1))
                    sb.Append(WriteElement("/item", Indent))



                End While
                dr.Close()
                sb.Append("<atom:link href=""http://" & HttpContext.Current.Request.Url.Host & HttpUtility.HtmlEncode(HttpContext.Current.Request.RawUrl) & """ rel=""self"" type=""application/rss+xml"" />")
                sb.Append(WriteElement("/channel", 1))
                sb.Append("</rss>")
                sb.Replace("[LASTBUILDDATE]", LastBuildDate.ToString("r"))
                DataCache.CacheStore("aftprss" & ModuleId, sb.ToString, DateTime.Now.AddMinutes(dblCacheTimeOut))
                Return sb.ToString
            Catch ex As Exception
                Return ex.ToString
            End Try


        End Function
    End Class

End Namespace
